// const lgurl="http://localhost:8889";
const lgurl = "https://app.lgwisdomunion.cn";
import boya from "./boya.js"
import config from "../../config.js"
export default {
	lgurl,
	//通过跳转方法
	nav_to(d, title = null, type = "nav", token = false, fullscreen = false) {
		console.log("nav_to", d, type);
		if (type == "mini") {
			//打开微信小程序
			this.wx_nav(d);
			return;
		}
		if (d.indexOf("wx:") >= 0) {
			//打开微信小程序
			let link = d.replace("wx:", "");
			// wx:gh_06d646894a5a,pages/activityhome/activityhome?caid=15&source=7003
			let arr = link.split(',');
			this.wx_nav({
				appid: arr[0],
				path: arr[1]
			});
			return;

		}

		//首页
		let Homes = ['index', 'my', 'serve', 'member', 'activity']
		if (Homes.indexOf(d) >= 0) {
			//转到首页
			uni.navigateTo({
				url: "/pages/switchPages/main?name=" + d
			})
			return;
		}


		// 处理后台H5页面，*/H5开头的URL（优先级更高）
		if (d.indexOf("*/H5/") >= 0) {
			// 将*/H5/替换为lg.boyaltd.cn/H5/
			let h5Url = d.replace("*/H5/", "https://lg.boyaltd.cn/H5/");
			console.log("后台H5页面跳转 h5Url:", h5Url);

			let pages = getCurrentPages();
			let back = pages[pages.length - 1].route;
			let Bearer = uni.getStorageSync("Bearer");
			
			// 统一使用web_full.vue，并传递Bearer参数
			let url = "/pages/web/web_full";
			url = url + "?url=" + encodeURIComponent(h5Url) + "&Bearer=" + Bearer;
			if (back) {
				url = url + "&back=" + encodeURIComponent(back);
			}
			if (title) {
				url = url + "&title=" + encodeURIComponent(title)
			}

			// 打印最终跳转的url
			console.log("最终uni.navigateTo跳转的url:", url);

			uni.navigateTo({
				url: url,
				fail: (err) => {
					console.log("nav->error", err)
					// 如果跳转失败，尝试直接打开外部链接
					// #ifdef H5
					window.open(h5Url, '_blank');
					// #endif
					// #ifdef APP-PLUS
					plus.runtime.openURL(h5Url);
					// #endif
				}
			});
			return;
		}

		if (d.substring(0, 1) == "*") {
			//装修编码器中，如果是*号开头代表new_app的H5版本，统一使用Bearer参数，不使用code
			//调转new_app,H5版本,h5的地址在/config.js中配置
			let _url = config.H5Url + "/#" + d.substring(1);

			let Bearer = uni.getStorageSync("Bearer");
			let url = "/pages/web/web";
			url = url + "?url=" + _url + "&Bearer=" + Bearer;
			uni.navigateTo({
				url: url
			})
			return;
		}



		if (d.substring(0, 1) == "#") {
			//#号开头为转到本项目的页面
			let url = d.substring(1).replace(" ", "").replace("\t", "").replace("\r", "");
			switch (type) {

				case "nav":
					uni.navigateTo({
						url: url,
						fail: (err) => {
							console.log("nav->error", err)
						}
					})
					break;
				case "reLaunch":
					uni.reLaunch({
						url: url,
						fail: (err) => {
							console.log("nav->error", err)
						}
					});
					break;
				case "redirectTo":
					uni.redirectTo({
						url: url,
						fail: (err) => {
							console.log("nav->error", err)
						}
					})
					break;
				case "tab":
					uni.switchTab({
						url: url,
						fail: (err) => {
							console.log("nav->error", err)
						}
					});
			}
			return;
		}
		if (d.substring(0, 4) == "http" || d.substring(0, 5) == "https") {

			// if(d.indexOf("app.lgwisdomunion")>0)
			// {
			// 	//d=d.replace("app.lgwisdomunion","lg.boyaltd.cn");
			// 	d=d.replace("app.lgwisdomunion",lgurl.replace("http://",""));
			// }
			let pages = getCurrentPages();
			console.log("nav_to->page", pages);

			let back = pages[pages.length - 1].route;
			console.log("nav_to->back", back);

			let url = "/pages/web/web";
			if (d.indexOf("full=1") > 0 || fullscreen) { //是否全屏
				url = "/pages/web/web_full";
			}
			url = url + "?token=" + token + "&url=" + encodeURIComponent(d) + "&back=" + encodeURIComponent(back);
			console.log("nav_to->url", url);
			if (title) {
				url = url + "&title=" + encodeURIComponent(title)
			}


			uni.navigateTo({
				url: url,
				fail: (err) => {
					console.log("nav->error", err)
					// 如果跳转失败，尝试直接打开外部链接
					// #ifdef H5
					window.open(d, '_blank');
					// #endif
					// #ifdef APP-PLUS
					plus.runtime.openURL(d);
					// #endif
				}
			});
		}

	},
	//微信小程序跳转  d={appid:小程序id,path：路径}
	wx_nav(d, token) {
		let _token = "";
		let self = this;
		if (token) {

			boya.NGet("/tpi/mcode", null, function(res) {
				console.log(res);
				if (d.path.indexOf("?") > 0) {
					d.path = d.path + "&code=" + res.data;
				} else {
					d.path = d.apth + "?code=" + res.data;
				}
				self.to_wx(d);
			})

		} else {
			this.to_wx(d);
		}

	},
	to_wx(d) {
		// #ifdef APP-PLUS
		console.log("get_server,plus", d);
		plus.share.getServices(function(s) {
			var shares = {};
			console.log("getServices", s);
			for (var i = 0; i < s.length; i++) {
				var t = s[i];
				console.log("getServices", t["id"]);
				if (t.id == "weixin") {
					let sweixin = t;
					console.log("weixin", d);
					sweixin.launchMiniProgram({
						id: d.id,
						path: d.path
					}, function(res) {
						console.log(res);
					}, function(err) {
						console.log(res);
					});
					break;
				}
			}
		}, function(e) {
			console.log("获取分享服务列表失败：" + e.message);
		});
		//#endif
	},
	toDate(d) {
		if (d) {
			if (d.indexOf(' ') > 0) {
				return d.split(' ')[0];
			}
		} else {
			return "";
		}
	},
	//是否为空判断
	isEmpty: function(obj) {
		if (obj == '') return true;
		if (obj == null) return true;
		if (obj == 'null') return true;
		if (obj === undefined) return true;
		return false;
	},
	checkWgt: function(success) {
		// #ifdef APP-PLUS
		let that = this;
		let appHj = 1;
		if (uni.getSystemInfoSync().platform == 'android') {
			appHj = 1;
		} else if (uni.getSystemInfoSync().platform == 'ios') {
			appHj = 2;
		}
		console.log("platform", appHj);

		plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
			console.log("getProperty", widgetInfo);
			//请求获取最新版本信息

			that.$boya.NGet("/app/getVer", {
				VersionType: appHj
			}, function(res) {
				console.log("/app/getVer", res);
				// });
				// that.RequestData({
				// 	url:that.getVersion,
				// 	data:{VersionType:appHj}
				// },(result)=>{
				let result = res.data;
				console.log(result, "checkWgt");
				//result={"VersionNumber":"2.7.5","VersionType":1,"Describe":"修复bug","versioncode":275,"QrCodeUrl":"https://tc.gxcbcmjt.com/cache/20221204/31b368ab5ecd42a182caad46b151469a.apk","IsHotUpdate":true,"MiniVer":"274","Id":79,"Guid":"32d5f1ce-a34b-4e02-8623-301d89d99bc1","CreatedDate":"2022-12-04 15:32:23","LastModifiedDate":"2022-12-04 15:32:23"} ;
				let minVersion = 0;


				let {
					version_code,
					content,
					version,
					is_wgt
				} = result;
				let down_url = result.url;
				if (result.hasOwnProperty("minVersion")) {
					minVersion = result.minVersion;
				}
				console.log("ver->minver,is_wgt", is_wgt);
				console.log(parseInt(widgetInfo.versionCode), parseInt(minVersion))
				// 如果安装的版本号小于最新发布的版本号，则进行更新
				if (parseInt(widgetInfo.versionCode) < parseInt(version_code)) {
					// 如果是热更新，则执行静默更新
					if (is_wgt == 1 && parseInt(widgetInfo.versionCode) > parseInt(minVersion)) {

						uni.showModal({
							title: "更新提示",
							content: "应用优化更新，是否需要更新应用？",
							success: (rex) => {
								if (rex.confirm) {
									// 下载wgt更新包
									uni.downloadFile({
										url: down_url,
										success: (downloadResult) => {
											if (downloadResult
												.statusCode === 200) {
												plus.runtime.install(
													downloadResult
													.tempFilePath, {
														force: true // 强制更新
													},
													function() {
														console.log(
															'热更新成功');
														uni.showModal({
															showCancel: false,
															title: "提示",
															content: "应用更新完成，需要重启应用",
															success: (
																rex2
															) => {
																if (rex2
																	.confirm
																) {
																	that
																		.nativeQuit();
																	// plus.runtime.restart();
																}
															}
														})
													},
													function(e) {
														console.error(
															'热更新失败，错误原因：' +
															e);
													});
											} else {
												console.log('下载wgt失败');
											}
										}
									})
								}
							}
						})
					} else {
						console.log('版本过低，请使用整包大版本更新');
						success(result);
					}
				} else {
					console.log('你的版本为最新，不需要更新');
				}
			})
		});
		// #endif
	},
	nativeQuit: function() {
		let _this = this;
		console.log("nativeQuit");
		uni.showToast({
			title: "准备重新启动！"
		});
		uni.getSystemInfo({
			success: function(e) {
				console.log(e.platform)
				Vue.prototype.StatusBar = e.statusBarHeight;
				Vue.prototype.$phoneInfo = e
				// let system = plus.android.import('java.lang.System')

				if (e.platform == 'android') {
					let main = plus.android.runtimeMainActivity();
					//  热更新之后需要杀死进程重新打开,需要引入安卓system的类来实现
					let system = plus.android.importClass('java.lang.System')
					system.exit(0);
				} else {
					plus.ios.import('UIApplication').sharedApplication().performSelector('exit');
				}
			}
		})
	},
	moveHanle() {},
	gx() {
		let that = this;

		if (uni.getSystemInfoSync().platform == 'android') {
			that.buttonText = "请稍等...";
			if (that.isreplace) {
				return;
			}
			that.isreplace = true;
			console.log("下载地址：" + that.gxInfo.url);
			const downloadTask = uni.downloadFile({
				url: that.gxInfo.url,
				success: (res) => {
					if (res.statusCode === 200) {
						that.progress = 100;
						that.buttonText = '下载完成,即将重启应用';
						plus.runtime.install(res.tempFilePath, {
							force: true // 强制更新
						}, function() {
							console.log("下载成功")
							that.$common.nativeQuit();
						}, function(error) {
							console.error('安装失败，错误原因：' + error);
							uni.showToast({
								title: '安装失败',
								icon: "error",
								duration: 1500
							});
						})
						setTimeout(res => {
							that.isreplace = false;
						}, 1000)
					}
				},
				complete: () => {}
			})
			downloadTask.onProgressUpdate((resx) => {
				console.log('下载进度' + resx.progress);
				that.progress = resx.progress;
			});
		} else if (uni.getSystemInfoSync().platform == 'ios') {
			plus.runtime.launchApplication({
				action: that.gxInfo.url
			}, function(e) {
				console.log('Open system default browser failed: ' + e.message);
			});
		}
	},
	getCss: function(d) {
		let ds = {};
		Object.assign(ds, d);

		delete ds["categorys"];
		delete ds["http"];
		delete ds["text"];
		delete ds["name"];
		delete ds["linktype"];
		delete ds["image-list"];


		if (ds == null || ds == "" || ds == undefined) return;
		// styleList=["backgroundImage","backgroundColor","color","textAlign","fontFamily","fontSize",]
		// console.log("set_style",ds)
		// return {}
		let arr = [];
		for (let d in ds) {
			if (ds[d] != "") {
				let key = this.replaceStyle(d);
				let val = ds[d];

				if (val != "" && val != null) {
					if (val instanceof String) {
						if (val.indexOf("px") > -1) {
							val = this.px2rpx(val);
						}
					}
				}
				if (typeof val == "string") {
					arr.push(key + ":" + val);
				}

			}
		}
		return arr.join(";");
	},
	px2rpx(styleString) {

		var convertedString = styleString.replace(/(\d+)px/g, function(match, p1) {
			// 将匹配到的px值转换为原值的两倍
			var newValue = 2 * parseFloat(p1);
			return newValue + 'rpx';
		});

		return convertedString;
	},
	replaceStyle(str) {
		if (typeof str !== 'string') {
			throw new Error('Input must be a string.');
		}

		if (!str) {
			return '';
		}

		const replaced = str.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
		return replaced;
	},
	get_appPages(fnc = null, loading = true, name = '首页') {
		//获取最新首页装修数据 
		let self = this;
		if (loading) {
			uni.showLoading({
				title: "页面更新中"
			});
		}
		boya.NPost("/app/appPages", {
			// name: "首页,导航条",
			// app: "柳钢之家",
			appid: config.appid,
			is_Preview: uni.getStorageSync("is_PreviewVer")
		}, (res) => {
			uni.hideLoading();
			console.log("app_page", res);
			let pages = [];
			res.data.map((item) => {

				let d = JSON.parse(item.json);
				if (d) {
					d.updated_at = item.updated_at;
					// console.log("appPages->d", d);

					if (item.type == "nav") {
						uni.setStorageSync("tabsConfig", d);
					} else {
						pages.push({
							name: item.name,
							json: d
						});
						if (name == 'all') {
							uni.setStorageSync("page_" + item.name, d);
						}
					}
				}
			})
			uni.setStorageSync("pages", pages);
			console.log("get_appPages", pages);
			if (fnc) {
				if (name == 'all') {
					fnc(pages);
				} else {
					for (let key in pages) {
						if (pages[key].name == name) {
							fnc(pages[key].json);
						}
					}
				}

			}

		}, null, {
			showLoading: loading
		});
	},
	get_page(name, update = false) {
		if (update == false) {
			let pages = uni.getStorageSync("pages");

			for (let key in pages) {
				if (pages[key].name == name) {
					return pages[key].json;
				}
			}
		} else {
			this.get_appPages(function(res) {
				return res;
			}, true, name);
		}
		return null;
	},
	home_data(data) {

		for (let key in data.component) {
			let item = data.component[key];

			if ([
					"graphicnavigation",
					"captiontext",
					"commoditysearch",
					"notice",
					"magiccube",
					"suspension",
					"storenotecard",
					"auxiliarysegmentation",
					"pictureads"
				].indexOf(item.component) != -1) {
				let id = "component_" + key;
				if (item.id) {
					id = item.id
				}
				item.id = id;
				item.key = "key_" + item.type;
			}
		}
		return data;

	},
	get_img(e) {

		let d = e;
		if (typeof(d) == 'string') {
			if (d.indexOf("{") >= 0) {
				d = JSON.parse(d);
				return d[0].url;
			}
		}
		return e;


	},
	check_img_url(img){
		//判断是否为http开头，如果是就直接返回，如果不是，就拼接
		
		if(img.indexOf("http")>=0){
			return img;
		}else{
			//判断img是否/开头
			if(img.substring(0,1)=="/"){
				return config.imghost+img;
			}else{
				return config.imghost+"/"+img;
			}
		}
		return img;
	},
	log(text) {
		let t = uni.getStorageSync("log");

		if (t == null) {
			t = text;
		} else {
			t = t + ";" + text;
		}
		uni.setStorageSync("log", t);
	},
	logout() {
		uni.showModal({
			title: '退出',
			content: "确定退出吗",
			success(e) {
				if (e.confirm) {
					// uni.removeStorageSync("userName");
					// uni.removeStorageSync("password");
					uni.removeStorageSync("member");
					uni.removeStorageSync("userInfo");
					uni.removeStorageSync("uuid");
					uni.removeStorageSync("ttsxAuthToken");
					uni.reLaunch({
						url: "/pages/login/login?logout=1"
					});
				}

			}
		})

	},
	web_url(parm) {
		var link = parm.url;
		let _url = ""
		let self = this;
		let member = uni.getStorageSync("member");
		let token = uni.getStorageSync("token");
		let user = uni.getStorageSync("userInfo")

		if (parm.url.indexOf("app.lgwisdomunion") > 0 || parm.url.indexOf("www.lgwisdomunion") > 0) {
			//"a6e38217-32c9-4c9e-8a69-1bc7cb563a50"
			let url = parm.url;
			url = url.split('#')[1];

			// let removeKey = ['orga', 'politicCountenance', 'political',
			// 	'procreationRemark', 'procreationStatus', 'education', 'educationalBackground', 'email',
			// 	'fileAge', 'fullTime', 'headPortrait', 'crtIp', 'crtTime', 'crtUser',
			// 	'updIp', 'updTime', 'updUser', 'speciality', 'maritalStatus', 'academicDegree',
			// 	'procreation_remark', 'procreation_status', 'politic_countenance', 'join_tradeUnion_time',
			// 	'join_company_time', 'academicDegree',
			// ]
			// for (let key in removeKey) {
			// 	delete user[removeKey[key]];
			// }
			_url = "https://app.lgwisdomunion.cn/#/loginx?code=" + parm.code + "&url=" + parm.url;


			return _url;
		}
		// if (parm.url.indexOf("jf.boyaltd") > 0) {
		if (parm.url.indexOf("jf.lgwisdomunion") > 0) {

			_url = parm.url;
			if (_url.charAt(_url.length - 1) == '/') {
				_url = _url.slice(0, -1);
			}
			return _url;

		} else {

			let Bearer = uni.getStorageSync("Bearer");

			link = link.replace("{uuid}", Bearer)



			link = link.replace("{name}", member.name)



			link = link.replace("{token}", token)

			link = link.replace("{userName}", member.lg_id)

			link = link.replace("{ttsxAuthToken}", token);

			let timestamp1 = new Date().getTime();
			link = link.replace("{timestamp}", timestamp1);

			link = link.replace("{ttsx_userid}", user.id);

			if (link.indexOf("{md5_sign}") >= 0) { //职工书屋用
				let host = link.substring(0, link.indexOf("?"));
				console.log("host", host);
				let urlparm = link.substring(link.indexOf("?"));

				let searchParams = self.StrToObj(urlparm);
				let paramsObj = {};
				for (let key in searchParams) {
					let value = searchParams[key];
					if (value.indexOf('{md5_sign}') == -1) {
						paramsObj[key] = value;
					}
				}
				// searchParams.forEach((value, param) => {
				// 	if(value!='{md5_sign}'){
				// 		paramsObj[param] = value;
				// 	}
				// });
				paramsObj["time"] = Date.parse(new Date()) / 1000 - 3600;
				let a = self.objToStr(paramsObj);
				let sign = grace.md5(a);
				paramsObj["sign"] = sign;
				link = host + "?" + self.objToStr(paramsObj);
				// let m="appID=lzgt&appKey=12fds4d6sg9pr66c9s57vva2c30l9ded&userName=19821024&userId=b73a7471-d415-45b5-9087-3fd3914b3093&time=1705318101";
				// console.log("md5",grace.md5(m));
			}
			return link;
		}
	},
	web_message(e, fnc = null) {
		console.log("getMessage", e);
		let data = e.detail.data[0];
		if (config.dev) {
			uni.showModal({
				title: 'web_message',
				content: JSON.stringify(data),
				showCancel: false
			})
		}
		console.log("data", JSON.stringify(data));
		if (data.type == "open_wexin") {
		
			console.log("直接打开小程序", JSON.stringify(data.data));
			this.wx_nav({
				id: data.data.app_id,
				path: data.data.path
			})
			
			
		}
		if (data.type == "open_wxpay") {
			uni.navigateTo({
				url: "/pages/pay/pay_info?data=" + encodeURIComponent(JSON.stringify(data)),
				fail(err) {
					console.log(err);
				}
			})
		}
		if (data.type == "open_abc") {
			uni.navigateTo({
				url: "/pages/pay/pay_info?data=" + encodeURIComponent(JSON.stringify(data)),
				fail(err) {
					console.log(err);
				}
			})
			return;
		}
		if (data.type == "Camera") {
			//打开摄像头
			// uni.createCameraContext().takePhoto({
			// 	success: (res) => {
			// 		console.log("createCameraContext",res);
			// 		fnc(res);
			// 	},
			// 	});
			return;
		}
		if (data.type == "album") {
			//打开相册
			console.log("打开相册");
			uni.chooseImage({
				count: 6, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: function(res) {
					console.log(JSON.stringify(res.tempFilePaths));
				}
			});
			return;
		}
	},
	update_app() {
		// 获取本地应用资源版本号。 app更新， 插件链接： https: //ext.dcloud.net.cn/plugin?id=7286
		// #ifdef APP-PLUS


		plus.runtime.getProperty(plus.runtime.appid, (inf) => {
			console.log('检查更新');
			self.$boya.NPost("/app/getVer", {
				edition_type: plus.runtime.appid,
				version_type: uni.getSystemInfoSync().platform, //android或者ios
				edition_number: inf.versionCode, // 打包时manifest设置的版本号 
				is_previewver: uni.getStorageSync("is_PreviewVer") // 不发行的版本更新
			}, function(res) {
				console.log("getVer->res", res);
				if (!res.data.hasOwnProperty("edition_number")) return;
				//res.data.xxx根据后台返回的数据决定（我这里后端返回的是data），所以是res.data.data
				//判断后台返回版本号是否大于当前应用版本号 && 是否发行 （上架应用市场时一定不能弹出更新提示）
				let is_PreviewVer = uni.getStorageSync("is_PreviewVer");
				let edition_issue = res.data.edition_issue == 1;
				console.log("is_PreviewVer", is_PreviewVer);
				if (is_PreviewVer) {
					edition_issue = true;
				}
				if (Number(res.data.edition_number) > Number(inf.versionCode) && edition_issue) {
					//如果是wgt升级，并且是静默更新 （注意！！！ 如果是手动检查新版本，就不用判断静默更新，请直接跳转更新页，不然点击检查新版本后会没反应）
					if (res.data.package_type == 1 && res.data.edition_silence == 1) {
						//调用静默更新方法 传入下载地址
						let is_restart = true;
						if (res.data.edition_force == 0) {
							is_restart = false;
						}
						console.log("silenceUpdate", res.data.edition_url);
						silenceUpdate(res.data.edition_url, is_restart)
					} else {
						//跳转更新页面 （注意！！！如果pages.json第一页的代码里有一打开就跳转其他页面的操作，下面这行代码最好写在setTimeout里面设置延时3到5秒再执行）
						setTimeout(function() {
							// 这里是要延迟执行的代码
							uni.navigateTo({
								url: '/uni_modules/rt-uni-update/components/rt-uni-update/rt-uni-update?obj=' +
									JSON.stringify(res.data)
							});
						}, 4000); // 5000毫秒等于5秒
					}
				} else {

					// 如果是手动检查新版本 需开启以下注释
					/* uni.showModal({
					    title: '提示',
					    content: '已是最新版本',
					    showCancel: false
					}) */
				}
			}, function(err) {
				console.log("检查更新失败-->err", err);
			});
			// , null, false
		});
		// #endif
	}


}